<template>
  <el-tabs v-model="activeName" class="demo-tabs" style="width: 100%;">
    <el-tab-pane label="请求参数" name="param">
      <el-collapse v-model="activeCollapse" class="param-collapse">
        <el-collapse-item name="param" title="参数配置" >
          <template #title>
            <div class="collapse-title">
              <el-icon class="title-icon">
                <List/>
              </el-icon>
              <span>参数配置</span>
              <el-badge :value="props.form.extData.filters?.length || 0" class="item-badge" type="primary"/>
            </div>
          </template>
          <sc-form-table v-model="props.form.extData.filters" drag-sort :addTemplate="addTemplate">
            <el-table-column width="210" align="center" label="显示名称">
              <template #default="scope">
                <el-input v-model="scope.row.fieldName"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="210" align="center" label="字段名称">
              <template #default="scope">
                <el-input v-model="scope.row.javaName"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="160" align="center" label="占位符">
              <template #default="scope">
                <el-input v-model="scope.row.placeholder"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="130" align="center" label="字段类型">
              <template #default="scope">
                <el-select
                    v-model="scope.row.fieldType"
                    placeholder="选择类型"
                >
                  <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="130" align="center" label="控件类型">
              <template #default="scope">
                <el-select
                    v-model="scope.row.inputType"
                    placeholder="控件类型"
                >
                  <el-option
                      v-for="item in inputOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="160" align="center" label="是否必传">
              <template #default="scope">
                <el-radio-group v-model="scope.row.required">
                  <el-radio-button label="必传" :value="1"/>
                  <el-radio-button label="非必传" :value="2"/>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column width="150" align="center" label="显示区域">
              <template #default="scope">
                <el-select v-model="scope.row.area" clearable placeholder="显示区域">
                  <el-option label="接口调用" :value="1"/>
                  <el-option label="主搜索" :value="2"/>
                  <el-option label="扩展搜索" :value="3"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="接口地址" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.queryUrl"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="100" align="center" fixed="right" label="操作">
              <template #default="scope">
                <el-button text class="operation_bt" :icon="Edit" type="primary" @click="editFilter(scope.row)">编辑
                </el-button>
              </template>
            </el-table-column>
          </sc-form-table>
          <div class="action-buttons">
            <el-button @click="addFilter" type="primary" :icon="Plus">添加过滤字段</el-button>
            <el-button @click="copyFilter" :icon="CopyDocument">复制过滤字段</el-button>
            <el-button @click="pasteFilter" :icon="DocumentCopy">粘贴过滤字段</el-button>
            <el-button @click="selectFilter" :icon="Search">选择过滤字段</el-button>
          </div>

          <select-dialog
              query-model="query_snippet_param_list"
              width="500px" title="选择参数集合"
              v-if="selectDialogVisible"
              @confirm="selectDialogConfirm"
              @cancel="selectDialogCancel"></select-dialog>
        </el-collapse-item>
      </el-collapse>
    </el-tab-pane>
    <el-tab-pane label="显示字段" name="field">
      <el-collapse v-model="activeCollapse" class="param-collapse">
        <el-collapse-item name="field" title="字段配置">
          <template #title>
            <div class="collapse-title">
              <el-icon class="title-icon">
                <Grid/>
              </el-icon>
              <span>字段配置</span>
              <el-badge :value="props.form.extData.fields?.length || 0" class="item-badge" type="success"/>
            </div>
          </template>
          <sc-form-table v-model="props.form.extData.fields" drag-sort :addTemplate="addFieldTemplate">
            <el-table-column width="200" align="center" label="显示名称">
              <template #default="scope">
                <el-input v-model="scope.row.title"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="200" align="center" label="取值key">
              <template #default="scope">
                <el-input v-model="scope.row.key"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="80" align="center" label="宽度">
              <template #default="scope">
                <el-input v-model="scope.row.width"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="100" align="center" label="是否显示">
              <template #default="scope">
                <el-switch
                    v-model="scope.row.showType"
                    :active-value="1"
                    :inactive-value="2"
                />
              </template>
            </el-table-column>
            <el-table-column width="100" align="center" label="是否排序">
              <template #default="scope">
                <el-switch
                    v-model="scope.row.sortType"
                    :active-value="1"
                    :inactive-value="2"
                />
              </template>
            </el-table-column>
            <el-table-column width="120" align="center" label="显示类型">
              <template #default="scope">
                <el-select
                    v-model="scope.row.fieldType"
                    placeholder="显示类型"
                >
                  <el-option label="图片" :value="1"/>
                  <el-option label="字符串" :value="2"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="120" align="center" label="固定位置">
              <template #default="scope">
                <el-select
                    v-model="scope.row.fixed"
                    placeholder="选择类型"
                >
                  <el-option label="左固定" value="left"/>
                  <el-option label="有固定" value="right"/>
                  <el-option label="不固定" value="none"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="排序号" width="70">
              <template #default="scope">
                <el-input v-model="scope.row.sortNum"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="跳转变量" width="160">
              <template #default="scope">
                <el-radio-group v-model="scope.row.useParam">
                  <el-radio-button label="取值" :value="1"/>
                  <el-radio-button label="不取值" :value="2"/>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column align="center" label="跳转变量名" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.param" :disabled="scope.row.useParam===2"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="导航类型" width="130">
              <template #default="scope">
                <el-radio-group v-model="scope.row.navType">
                  <el-radio-button label="跳转" :value="1"/>
                  <el-radio-button label="无" :value="2"/>
                </el-radio-group>
              </template>
            </el-table-column>

            <el-table-column align="center" label="跳转地址" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.navUrl" :disabled="scope.row.navType===2"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="权限校验" width="130">
              <template #default="scope">
                <el-radio-group v-model="scope.row.auth">
                  <el-radio-button label="校验" :value="1"/>
                  <el-radio-button label="不" :value="2"/>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column align="center" label="权限标签" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.authKey" :disabled="scope.row.auth===2"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="100" align="center" fixed="right" label="操作">
              <template #default="scope">
                <el-button text class="operation_bt" :icon="Edit" type="primary" @click="editView(scope.row)">编辑
                </el-button>
              </template>
            </el-table-column>
          </sc-form-table>
          <div class="action-buttons">
            <el-button @click="addField" type="primary" :icon="Plus">添加显示字段</el-button>
            <el-button @click="copyField" :icon="CopyDocument">复制显示字段</el-button>
            <el-button @click="pasteField" :icon="DocumentCopy">粘贴显示字段</el-button>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-tab-pane>
    <el-tab-pane label="排序字段" name="sortField">
      <el-collapse v-model="activeCollapse" class="param-collapse">
        <el-collapse-item name="sortField" title="排序配置">
          <template #title>
            <div class="collapse-title">
              <el-icon class="title-icon">
                <Sort/>
              </el-icon>
              <span>排序配置</span>
              <el-badge :value="props.form.extData.sortNames?.length || 0" class="item-badge" type="warning"/>
            </div>
          </template>
          <sc-form-table v-model="props.form.extData.sortNames" drag-sort :addTemplate="addSortTemplate">
            <el-table-column width="200" align="center" label="排序名称">
              <template #default="scope">
                <el-input v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="排序数据库字段">
              <template #default="scope">
                <el-input v-model="scope.row.dbName"></el-input>
              </template>
            </el-table-column>
          </sc-form-table>
          <div class="action-buttons">
            <el-button @click="addSort" type="primary" :icon="Plus">添加排序字段</el-button>
            <el-button @click="copySort" :icon="CopyDocument">复制排序字段</el-button>
            <el-button @click="pasteSort" :icon="DocumentCopy">粘贴排序字段</el-button>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-tab-pane>
    <el-tab-pane label="数据汇总" name="aggregates">
      <el-collapse v-model="activeCollapse" class="param-collapse">
        <el-collapse-item name="aggregates" title="汇总字段">
          <template #title>
            <div class="collapse-title">
              <el-icon class="title-icon">
                <Grid/>
              </el-icon>
              <span>字段配置</span>
              <el-badge :value="props.form.extData.aggregates?.length || 0" class="item-badge" type="success"/>
            </div>
          </template>
          <sc-form-table v-model="props.form.extData.aggregates" drag-sort :addTemplate="addAggregateTemplate">
            <el-table-column width="200" align="center" label="显示名称">
              <template #default="scope">
                <el-input v-model="scope.row.title"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="200" align="center" label="汇总字段">
              <template #default="scope">
                <el-input v-model="scope.row.field"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="200" align="center" label="聚合函数">
              <template #default="scope">
                <el-select
                    v-model="scope.row.func"
                    placeholder="选择类型"
                >
                  <el-option
                      v-for="item in funcOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="200" align="center" label="别名">
              <template #default="scope">
                <el-input v-model="scope.row.alias"></el-input>
              </template>
            </el-table-column>
            <el-table-column   align="center" label="小数保留位数">
              <template #default="scope">
                <el-input v-model="scope.row.scale"></el-input>
              </template>
            </el-table-column>
          </sc-form-table>
          <div class="action-buttons">
            <el-button @click="addAggregate" type="primary" :icon="Plus">添加汇总字段</el-button>
            <el-button @click="copyAggregate" :icon="CopyDocument">复制汇总字段</el-button>
            <el-button @click="pasteAggregate" :icon="DocumentCopy">粘贴汇总字段</el-button>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-tab-pane>
  </el-tabs>
  <!-- 编辑显示字段对话框 -->
  <el-dialog
      v-model="editDialogVisible"
      title="编辑显示字段"
      width="760px"
      @close="onEditDialogClose"
  >
    <el-form :model="editForm" label-width="110px" label-position="left" class="edit-form">
      <el-form-item label="显示名称">
        <el-input v-model="editForm.title" placeholder="请输入显示名称"/>
      </el-form-item>
      <el-form-item label="取值key">
        <el-input v-model="editForm.key" placeholder="请输入取值key"/>
      </el-form-item>
      <el-form-item label="宽度">
        <el-input v-model="editForm.width" placeholder="例如：120 或 12%"/>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch v-model="editForm.showType" :active-value="1" :inactive-value="2"/>
      </el-form-item>
      <el-form-item label="是否排序">
        <el-switch v-model="editForm.sortType" :active-value="1" :inactive-value="2"/>
      </el-form-item>
      <el-form-item label="显示类型">
        <el-select v-model="editForm.fieldType" placeholder="显示类型">
          <el-option label="图片" :value="1"/>
          <el-option label="字符串" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="固定位置">
        <el-select v-model="editForm.fixed" placeholder="选择类型">
          <el-option label="左固定" value="left"/>
          <el-option label="有固定" value="right"/>
          <el-option label="不固定" value="none"/>
        </el-select>
      </el-form-item>
      <el-form-item label="排序号">
        <el-input v-model="editForm.sortNum" placeholder="请输入排序号"/>
      </el-form-item>
      <el-form-item label="跳转变量">
        <el-radio-group v-model="editForm.useParam">
          <el-radio-button label="取值" :value="1"/>
          <el-radio-button label="不取值" :value="2"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="变量名">
        <el-input v-model="editForm.param" :disabled="editForm.useParam===2" placeholder="请输入跳转变量名"/>
      </el-form-item>
      <el-form-item label="导航类型">
        <el-radio-group v-model="editForm.navType">
          <el-radio-button label="跳转" :value="1"/>
          <el-radio-button label="无" :value="2"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="跳转地址">
        <el-input
            v-model="editForm.navUrl"
            type="textarea"
            :rows="2"
            :disabled="editForm.navType===2"
            placeholder="请输入跳转地址"
        />
      </el-form-item>
      <el-form-item label="权限校验">
        <el-radio-group v-model="editForm.auth">
          <el-radio-button label="校验" :value="1"/>
          <el-radio-button label="不" :value="2"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限标签">
        <el-input v-model="editForm.authKey" :disabled="editForm.auth===2" placeholder="请输入权限标签"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onEditDialogClose">取 消</el-button>
        <el-button type="primary" @click="saveEdit">保 存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑请求参数对话框 -->
  <el-dialog
      v-model="editFilterDialogVisible"
      title="编辑请求参数"
      width="600px"
      @close="onEditFilterDialogClose"
  >
    <el-form :model="editFilterForm" label-width="110px" label-position="left" class="edit-form">
      <el-form-item label="显示名称">
        <el-input v-model="editFilterForm.fieldName" placeholder="请输入显示名称"/>
      </el-form-item>
      <el-form-item label="字段名称">
        <el-input v-model="editFilterForm.javaName" placeholder="请输入字段名称"/>
      </el-form-item>
      <el-form-item label="占位符">
        <el-input v-model="editFilterForm.placeholder" placeholder="请输入占位符"/>
      </el-form-item>
      <el-form-item label="字段类型">
        <el-select v-model="editFilterForm.fieldType" placeholder="选择类型">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="控件类型">
        <el-select v-model="editFilterForm.inputType" placeholder="控件类型">
          <el-option
              v-for="item in inputOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否必传">
        <el-radio-group v-model="editFilterForm.required">
          <el-radio-button label="必传" :value="1"/>
          <el-radio-button label="非必传" :value="2"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="显示区域">
        <el-select v-model="editFilterForm.area" clearable placeholder="显示区域">
          <el-option label="接口调用" :value="1"/>
          <el-option label="主搜索" :value="2"/>
          <el-option label="扩展搜索" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="接口地址">
        <el-input
            v-model="editFilterForm.queryUrl"
            type="textarea"
            :rows="2"
            placeholder="请输入接口地址"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onEditFilterDialogClose">取 消</el-button>
        <el-button type="primary" @click="saveFilterEdit">保 存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {onMounted, ref, watch, nextTick} from "vue";
import {ElMessage} from "element-plus";
import scFormTable from "@/components/scFormTable/index.vue";
import SelectDialog from "@/components/SelectDialog.vue";
import http from "@/utils/request";
import {copy} from "@/utils/clipboardUtil";
import {
  Edit,
  ArrowDown,
  ArrowUp,
  List,
  Grid,
  Sort,
  Plus,
  CopyDocument,
  DocumentCopy,
  Search
} from "@element-plus/icons-vue";


const selectDialogVisible = ref(false);
const editDialogVisible = ref(false);
const editForm = ref({});
const editingTargetRow = ref(null);

// 请求参数编辑相关状态
const editFilterDialogVisible = ref(false);
const editFilterForm = ref({});
const editingFilterTargetRow = ref(null);

const options = ref([

  {
    label: "字符数组",
    value: 10
  },
  {
    label: "字符串",
    value: 1
  },
  {
    label: "整型",
    value: 2
  },
  {
    label: "长整型",
    value: 3
  },
  {
    label: "单对象",
    value: 401
  },
  {
    label: "集合对象",
    value: 402
  },
  {
    label: "map对象",
    value: 13
  },
  {
    label: "json对象",
    value: 200
  },
  {
    label: "json数组",
    value: 201
  },
  {
    label: "浮点数",
    value: 4
  },
  {
    label: "对象",
    value: 9
  },
  {
    label: "整形数组",
    value: 11
  },
  {
    label: "小数数组",
    value: 12
  },
  {
    label: "BigDecimal",
    value: 5
  },
  {
    label: "日期",
    value: 6
  }, {
    label: "字符输入",
    value: 101
  },
  {
    label: "布尔",
    value: 7
  },
  {
    label: "枚举",
    value: 8
  }

])

const inputOptions = ref([
  {
    label: "多选框",
    value: 6
  },
  {
    label: "日期区间",
    value: 8
  },
  {
    label: "时间区间",
    value: 9
  },
  {
    label: "下拉单选框",
    value: 2
  },
  {
    label: "输入框",
    value: 1
  },

  {
    label: "日期",
    value: 3
  },
  {
    label: "时间",
    value: 4
  },
  {
    label: "日期时间",
    value: 5
  },
  {
    label: "开关",
    value: 7
  }

])


const funcOptions = ref([
  {
    label: "sum",
    value: "sum"
  },
  {
    label: "count",
    value: "count"
  },
  {
    label: "max",
    value: "max"
  },
  {
    label: "min",
    value: "min"
  },
  {
    label: "avg",
    value: "avg"
  }
])
const addTemplate = ref({
  fieldName: null,
  javaName: null,
  fieldType: null
})

const addAggregateTemplate = ref({
  field: null,
  func: null,
  alias: null
})


const addFieldTemplate = ref({
  title: null,
  width: null,
  key: null,
  showType: 1,
  fieldType: 2
})

const addSortTemplate = ref({
  name: null,
  dbName: null
})

// 定义 props，必须在所有使用 props 的代码之前
const props = defineProps({
  form: {
    type: Object,
    default: {}
  },
});

const activeName = ref('param')

// 折叠面板激活状态 - 默认展开所有面板
const activeCollapse = ref(['param', 'field', 'sortField','aggregates'])

// 标志位，用于避免循环更新
const isUpdatingFromExpandFilter = ref(false)

// 根据 expandFilter 控制参数配置面板的展开/折叠
watch(() => props.form.extData?.expandFilter, (newVal) => {
  if (isUpdatingFromExpandFilter.value) return
  
  if (newVal === 1) {
    // 展开：确保 'param' 在数组中
    if (!activeCollapse.value.includes('param')) {
      activeCollapse.value.push('param')
    }
  } else if (newVal === -1) {
    // 折叠：从数组中移除 'param'
    const index = activeCollapse.value.indexOf('param')
    if (index > -1) {
      activeCollapse.value.splice(index, 1)
    }
  }
}, { immediate: true })

// 监听 activeCollapse 的变化，同步更新 expandFilter（仅针对 param 面板）
watch(activeCollapse, (newVal) => {
  if (isUpdatingFromExpandFilter.value) return
  
  const isParamExpanded = newVal.includes('param')
  if (props.form.extData) {
    isUpdatingFromExpandFilter.value = true
    props.form.extData.expandFilter = isParamExpanded ? 1 : -1
    // 使用 nextTick 确保更新完成后再重置标志
    nextTick(() => {
      isUpdatingFromExpandFilter.value = false
    })
  }
})
const addField = () => {
  if (!props.form.extData.fields) {
    props.form.extData.fields = [];
  }

  props.form.extData.fields.push({
    title: null,
    width: null,
    key: null,
    showType: 1,
    fieldType: 2
  })
}

onMounted(()=>{

  setTimeout(()=>{
    if (!props.form.extData.filters){
      props.form.extData.filters = [];
    }
    if (!props.form.extData.fields){
      props.form.extData.fields = [];
    }
    if (!props.form.extData.sorts){
      props.form.extData.sorts = [];
    }
    if (!props.form.extData.aggregates){
      props.form.extData.aggregates = [];
    }

  },1000);



})


const copyField = () => {
  if (props.form.extData.fields.length > 0) {
    //json话过滤参数 复制到剪贴板上
    let json = JSON.stringify(props.form.extData.fields);

    let clipboard = navigator.clipboard || {
      writeText: (text) => {
        let copyInput = document.createElement('input');
        copyInput.value = text;
        document.body.appendChild(copyInput);
        copyInput.select();
        document.execCommand('copy');
        document.body.removeChild(copyInput);
      }
    }
    if (clipboard) {
      clipboard.writeText(json);
      ElMessage({
        message: '复制成功',
        type: 'success',
      })
    }


  }
}

function addFilters(newFields) {
  const existingKeys = props.form.extData.filters.map(item => item.javaName);

  // 过滤掉已存在的key
  const uniqueFields = newFields.filter(item =>
      item.javaName && !existingKeys.includes(item.javaName)
  );

  if (uniqueFields.length > 0) {
    props.form.extData.filters = [...props.form.extData.filters, ...uniqueFields];
    ElMessage({
      message: `粘贴成功，新增${uniqueFields.length}个字段`,
      type: 'success',
    })
  } else {
    ElMessage({
      message: '所有字段都已存在，未添加重复字段',
      type: 'warning',
    })
  }
}

const pasteField = () => {
  navigator.clipboard.readText().then(function (clipText) {
    const newFields = JSON.parse(clipText);
    addFields(newFields);


  });
}

const addFilter = () => {
  if (!props.form.extData) {
    props.form.extData = {};
  }
  if (!props.form.extData.filters) {
    props.form.extData.filters = [];
  }
  props.form.extData.filters.push({
    fieldName: null,
    javaName: null,
    fieldType: null
  })
}

const addFields = (newFields) => {
  const existingKeys = props.form.extData.fields.map(item => item.key);

  // 过滤掉已存在的key
  const uniqueFields = newFields.filter(item =>
      item.key && !existingKeys.includes(item.key)
  );

  if (uniqueFields.length > 0) {
    props.form.extData.fields = [...props.form.extData.fields, ...uniqueFields];
    ElMessage({
      message: `粘贴成功，新增${uniqueFields.length}个字段`,
      type: 'success',
    })
  } else {
    ElMessage({
      message: '所有字段都已存在，未添加重复字段',
      type: 'warning',
    })
  }
}

const addAggregate = () => {
  if (!props.form.extData) {
    props.form.extData = {};
  }
  if (!props.form.extData.aggregates) {
    props.form.extData.aggregates = [];
  }
  props.form.extData.aggregates.push({
    field: null,
    func: null,
    alias: null
  })
}
const copyAggregate = () => {
  if (props.form.extData.aggregates.length > 0) {
    //json话过滤参数 复制到剪贴板上
    let json = JSON.stringify(props.form.extData.aggregates);

    copy(json, (status, message) => {
      if (status === 'success') {
        ElMessage.success(message)
      } else {
        ElMessage.error('复制失败')
      }
    })
  }
}
const addAggregates = (newFields) => {
  const existingKeys = props.form.extData.aggregates.map(item => item.field);

  // 过滤掉已存在的key
  const uniqueFields = newFields.filter(item =>
      item.field && !existingKeys.includes(item.field)
  );

  if (uniqueFields.length > 0) {
    props.form.extData.aggregates = [...props.form.extData.aggregates, ...uniqueFields];
    ElMessage({
      message: `粘贴成功，新增${uniqueFields.length}个字段`,
      type: 'success',
    })
  } else {
    ElMessage({
      message: '所有字段都已存在，未添加重复字段',
      type: 'warning',
    })
  }
}
const pasteAggregate = () => {
  navigator.clipboard.readText().then(function (clipText) {
    const newFilters = JSON.parse(clipText);
    addAggregates(newFilters);
  });
}


const copyFilter = () => {
  if (props.form.extData.filters.length > 0) {
    //json话过滤参数 复制到剪贴板上
    let json = JSON.stringify(props.form.extData.filters);
    // navigator.clipboard.writeText(json).then(function () {
    //   ElMessage({
    //     message: '复制成功',
    //     type: 'success',
    //   })
    // }, function (err) {
    //   console.error('Async: Could not copy text: ', err);
    // });


    copy(json, (status, message) => {
      if (status === 'success') {
        ElMessage.success(message)
      } else {
        ElMessage.error('复制失败')
      }
    })
  }
}

const pasteFilter = () => {
  navigator.clipboard.readText().then(function (clipText) {
    const newFilters = JSON.parse(clipText);
    addFilters(newFilters);
  });
}

const addSort = () => {
  if (!props.form.extData.sortNames) {
    props.form.extData.sortNames = [];
  }
  props.form.extData.sortNames.push({
    name: null,
    dbName: null
  })
}


const copySort = () => {
  if (props.form.extData.fields.length > 0) {
    //json话过滤参数 复制到剪贴板上
    let json = JSON.stringify(props.form.extData.sortNames);
    navigator.clipboard.writeText(json).then(function () {
      ElMessage({
        message: '复制成功',
        type: 'success',
      })
    }, function (err) {
      console.error('Async: Could not copy text: ', err);
    });
  }
}

const pasteSort = () => {
  navigator.clipboard.readText().then(function (clipText) {
    const newSortNames = JSON.parse(clipText);
    const existingNames = props.form.extData.sortNames.map(item => item.name);

    // 过滤掉已存在的name
    const uniqueSortNames = newSortNames.filter(item =>
        item.name && !existingNames.includes(item.name)
    );

    if (uniqueSortNames.length > 0) {
      props.form.extData.sortNames = [...props.form.extData.sortNames, ...uniqueSortNames];
      ElMessage({
        message: `粘贴成功，新增${uniqueSortNames.length}个字段`,
        type: 'success',
      })
    } else {
      ElMessage({
        message: '所有字段都已存在，未添加重复字段',
        type: 'warning',
      })
    }
  });
}


const selectFilter = () => {
  selectDialogVisible.value = true;
}

const selectDialogCancel = () => {
  selectDialogVisible.value = false;
}

const selectDialogConfirm = async (row) => {

  let param = {
    id: row.id
  }
  let res = await http.post("/querySnippetParam/view", param);
  if (res.code === 200) {
    addFilters(res.data.extData.filters)
  }
}


const editView = (row) => {
  editingTargetRow.value = row;
  // 深拷贝一份用于表单编辑，避免未保存时即改动原数据
  editForm.value = JSON.parse(JSON.stringify(row || {}));
  // 合理的默认值，防止未定义导致控件禁用判断异常
  if (editForm.value.showType === undefined) editForm.value.showType = 1;
  if (editForm.value.sortType === undefined) editForm.value.sortType = 2;
  if (editForm.value.fieldType === undefined) editForm.value.fieldType = 2;
  if (editForm.value.navType === undefined) editForm.value.navType = 2;
  if (editForm.value.useParam === undefined) editForm.value.useParam = 2;
  if (editForm.value.auth === undefined) editForm.value.auth = 2;
  if (editForm.value.fixed === undefined) editForm.value.fixed = 'none';
  editDialogVisible.value = true;
}

const onEditDialogClose = () => {
  editDialogVisible.value = false;
  editingTargetRow.value = null;
  editForm.value = {};
}

const saveEdit = () => {
  if (!editingTargetRow.value) {
    onEditDialogClose();
    return;
  }
  Object.assign(editingTargetRow.value, editForm.value);
  ElMessage.success('保存成功');
  onEditDialogClose();
}

// 请求参数编辑相关方法
const editFilter = (row) => {
  editingFilterTargetRow.value = row;
  // 深拷贝一份用于表单编辑，避免未保存时即改动原数据
  editFilterForm.value = JSON.parse(JSON.stringify(row || {}));
  // 设置合理的默认值，防止未定义导致控件异常
  if (editFilterForm.value.fieldType === undefined) editFilterForm.value.fieldType = 1;
  if (editFilterForm.value.inputType === undefined) editFilterForm.value.inputType = 1;
  if (editFilterForm.value.required === undefined) editFilterForm.value.required = 2;
  if (editFilterForm.value.area === undefined) editFilterForm.value.area = null;
  editFilterDialogVisible.value = true;
}

const onEditFilterDialogClose = () => {
  editFilterDialogVisible.value = false;
  editingFilterTargetRow.value = null;
  editFilterForm.value = {};
}

const saveFilterEdit = () => {
  if (!editingFilterTargetRow.value) {
    onEditFilterDialogClose();
    return;
  }
  Object.assign(editingFilterTargetRow.value, editFilterForm.value);
  ElMessage.success('保存成功');
  onEditFilterDialogClose();
}

</script>
<style scoped>
.edit-form :deep(.el-form-item) {
  margin-bottom: 10px;
}

.param-collapse {
  border: none;
  background: transparent;
}

.param-collapse :deep(.el-collapse-item__header) {
  background: transparent;
  border: none;
  padding: 12px 0;
  margin-bottom: 10px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.param-collapse :deep(.el-collapse-item__header:hover) {
  background: transparent;
  color: #409eff;
}

.param-collapse :deep(.el-collapse-item__content) {
  padding: 0;
  border: none;
}

.param-collapse :deep(.el-collapse-item__wrap) {
  border: none;
}

.collapse-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #2c3e50;
  font-size: 14px;

}

.title-icon {
  font-size: 16px;
  color: #409eff;
}

.item-badge {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.action-buttons {
  margin-top: 15px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.param-collapse :deep(.el-collapse-item) {
  border: none;
  margin-bottom: 8px;
}

.param-collapse :deep(.el-collapse-item:last-child) {
  margin-bottom: 0;
}

.param-collapse :deep(.el-collapse-item__arrow) {
  font-size: 14px;
  color: #409eff;
  transition: all 0.3s ease;
}

.param-collapse :deep(.el-collapse-item__header.is-active .el-collapse-item__arrow) {
  color: #67c23a;
}
</style>
